// 先引入mockjs模块
import Mock from 'mockjs'
// 把JSON数据格式引入进来
import stuInfo from './stuInfo.json';
import moment from 'moment'

// 数据键名转化
const changeKey = (data) => {
  const keyMap = { 
    stu_name: 'stuName',
    stu_ID: 'stuID', 
    stu_pwd: 'stuPwd', 
    stu_account: 'stuAccount',
    stu_school: 'school',
    stu_class: 'stuClass',
    stu_address: 'address',
    stu_phone: 'phone',
  }
  // 将对象键名改为stuInfo对应的键名，用于渲染
  // Object.keys()获取对象键名（此处为stu_name、stu_ID等等）
  // reduce()对数组每个元素按序执行reducer函数，每一次运行reducer会将先前元素的计算结果作为参数传入，最后将其结果汇总为单个返回值。
  // 对datas的键名进行reduce遍历，newKey为keyMap(自定义的键名数据)对应的值，
  const newDatas = Object.keys(data).reduce((newData, key) => {
    let newKey = keyMap[key] || key  // 第一次keyMap[key]值为stuName,key为stu_name
    newData[newKey] = data[key]  // 将datas中stuName对应的值赋给newData中属性为stuName键值
    return newData
  }, {})
  newDatas['time'] = moment().format('YYYY-MM-DD HH:mm:ss')
  return newDatas
}

// mock数据:第一个参数请求地址  第二个参数请求数据
// 获取/查找数据
Mock.mock("/mock/stuInfo", (...argument) => {
  let hasInfo = true
  let isCorrect 
  if (argument[0].body == null) {
    hasInfo = !hasInfo
  }
  let searchData = []
  if (hasInfo) {
    let datas = JSON.parse(argument[0].body)
    const stuName = datas.stuName
    const stuAccount = datas.stuAccount
    const school = datas.school
    for (let i in stuInfo) {
      // 假设两个输入框中只填入一个信息
      // 1. 只填入学生姓名信息
      // 2. 只填入学生账号信息
      if (!stuName || !stuAccount) {
        if (!stuName) {
          if (!school) {
            if (stuInfo[i].stuAccount == stuAccount) {
              isCorrect = true
              searchData.push(stuInfo[i]);
            } 
          } else {
            if (stuInfo[i].stuAccount == stuAccount && stuInfo[i].school == school) {
              isCorrect = true
              searchData.push(stuInfo[i]);
            } 
          }
        } else if (stuName){
          if (!school) {
            if (stuInfo[i].stuName == stuName) {
              isCorrect = true
              searchData.push(stuInfo[i]);
            } 
          } else {
            if (stuInfo[i].stuName == stuName && stuInfo[i].school == school) {
              isCorrect = true
              searchData.push(stuInfo[i]);
            } 
          }
        }
      } 
      // 填入两个信息
      // 填写正确
      // 任一填写错误
      else if ( stuName && stuAccount ) {
        if (!school) {
          if ( stuInfo[i].stuName == stuName && stuInfo[i].stuAccount == stuAccount ) {
            isCorrect = true
            searchData.push(stuInfo[i]);
          } 
        } else {
          if ( stuInfo[i].stuName == stuName && stuInfo[i].stuAccount == stuAccount && stuInfo[i].school == school) {
            isCorrect = true
            searchData.push(stuInfo[i]);
          } 
        }
      } 
    }
  }
  let data={
    data: hasInfo? searchData:stuInfo,
    code: 200,
    msg: isCorrect?  '查询成功':'查询信息有误'
  }
  return data
});  

// 请求删除数据
Mock.mock(RegExp('/mock/stuInfo/delete'+ '*'),  (deleteInfo) => {
  // 此时的deleteInfo是 {url: '/mock/stuInfo/delete?stuID=1', type: 'DELETE', body: null}
  const {url} = deleteInfo
  // 从url中获取到stuID
  let stuID = url.substr(27)
  for (let i in stuInfo) {
    // 在stuInfo对应id的数组中找到对应id
    if(stuInfo[i].stuID == stuID ){
      // 把这个id对应的数据从数组里删除
      stuInfo.splice(i,1)
    }
  }
  const data = {
    data: stuInfo,
    code: 200,
    msg: '删除成功'
  }
  return data
}); 

// 请求添加数据
Mock.mock("/mock/stuInfo/add",(addInfo) => {
  // 解析datas字符串 构造js对象 
  let datas = JSON.parse(addInfo.body)
  datas['time'] = moment().format('YYYY-MM-DD HH:mm:ss')
  let stuID = datas.stuID
  let isExist = true
  for(let i in stuInfo) {
    if(stuInfo[i].stuID == stuID) {
      isExist = !isExist
    }
  }
  let data = {
    data: isExist ? stuInfo.push(datas) : stuInfo,
    code: 200 ,
    msg: isExist ? '添加成功' : '添加失败！数据已存在'
  }
  return data
}); 

// 请求编辑数据
Mock.mock("/mock/stuInfo/edit", (editInfo) => {
  /** 此时的editInfo是
   * {
   *  "stu_name":"小周周", => stuName
   *  "stu_ID":"122",   =>   stuID
   *  "stu_pwd":"111",  =>   stuPwd
   *  "stu_account":"111", => stuAccount
   *  "stu_school":"111", => school
   *  "stu_class":"111", =>  stuClass
   *  "stu_address":"111", => address
   *  "stu_phone":"12323143535" => phone
   * }
  */
  let datas = JSON.parse(editInfo.body)
  const editData = changeKey(datas)
  let stuID = editData.stuID
  for(let i in stuInfo){
    if(stuInfo[i].stuID == stuID){//在数组arr里找到这个id
      stuInfo[i] = editData;
    }  
  }
  let data={
    data: editData,
    code: 200 ,
    msg: "编辑成功！"
  }
  return data
})

// 请求查找数据
// Mock.mock("/mock/stuInfo/search", )
